package com.rmkj.trade.match.util;

import java.io.*;

/**
 * Created by Administrator on 2019/1/14.
 */
public class TempDataUtils {

	private final static String TMPDIR = System.getProperty("java.io.tmpdir");
	private final static String SUFFIX = ".tdu";
	private static String group = null;

	private static boolean isInit(){
		return !(TempDataUtils.group == null || "".equalsIgnoreCase(TempDataUtils.group.trim()));
	}


	public synchronized static void init(String group){
		if(!isInit()){
			TempDataUtils.group = group;
		}
	}

	public static String read(String key){
		if(isInit()){
			File file = new File(TMPDIR, TempDataUtils.group.concat("-").concat(key).concat(SUFFIX));
			if (file.exists()) {
				try(FileReader fis = new FileReader(file)){
					char[] bb = new char[10];
					int aa;
					StringBuilder sb = new StringBuilder();
					while ((aa = fis.read(bb)) != -1) {
						sb.append(bb, 0 , aa);
					}
					return sb.toString();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}

	public static void write(String key, String content){
		if(isInit()){
			File file = new File(TMPDIR, TempDataUtils.group.concat("-").concat(key).concat(SUFFIX));
			try(FileWriter fis = new FileWriter(file)){
				fis.write(content);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
